#!/usr/bin/perl

use strict;

my @samples=map sin(2*3.141592635*$_/32),(0..31);
my $rate=128;
my $name=".bangaio-tmp";

my $size=3*$rate/2;

print "#include <sys/types.h>\n";
print "\n";
print "u_int8_t mpeg_frames[4097][$size]={\n";

open ALL,">all.mpg";

foreach my $n (0..4095)
#foreach my $n (0,0,0,0x801,0xfaf,0x6a6,0x801,0,0,0)
{
	open FILE,">$name.pcm";

	for(0..14) # 14? what the hell?
	{
		foreach my $sample (@samples) { print FILE pack "n",int(32767*$sample*0.7)&65535 }
	}

	foreach my $bit (0..11)
	{
		foreach my $sample (@samples)
		{
#			my $amp=$n&(0x800>>$bit)?1:0.4;
			my $amp=$n&(1<<$bit)?1:0.4;
			print FILE pack "n",int(32767*$sample*$amp)&65535;
		}
	}

	for(0..23)
	{
		foreach my $sample (@samples) { print FILE pack "n",int(32767*$sample*0.7)&65535 }
	}

	close FILE;

	`./encode -l 1 -m m -p 1 -s 32 -b $rate -d n $name.pcm $name.mpg 2>/dev/null`;

	open FILE,"$name.mpg";
	seek FILE,$size*2,0;
	read FILE,my $buf,$size;
	close FILE;

	print ALL $buf;

	print "\t{ ";
	print join ",",map { sprintf("0x%02x",ord($_)) } split //,$buf;
	print " },\n";
}


# do quiet frame

open FILE,">$name.pcm";
for(0..384*5-1) { print FILE pack "n",0 }
close FILE;

`./encode -l 1 -m m -p 1 -s 32 -b $rate -d n $name.pcm $name.mpg 2>/dev/null`;

open FILE,"$name.mpg";
seek FILE,$size*2,0;
read FILE,my $buf,$size;
close FILE;

print ALL $buf;

#print "\t{ ";
#print join ",",map { sprintf("0x%02x",ord($_)) } split //,$buf;
#print " },\n";


print ALL pack "c",0;
close ALL;

print "};\n";

unlink ".$name.pcm";
unlink ".$name.mpg";
